package algebra.rewriting.relational;

import algebra.op.AlgebraicOP;
import algebra.op.ProjectionOP;
import algebra.op.ScanOP;
import algebra.rewriting.RewriteRule;

public class RemoveProjection extends RewriteRule {
	private final AlgebraicOP op;

	public RemoveProjection(AlgebraicOP op) {
		this.op = op;
	}

	// if Prj_pd(Scan Si(Q)) and Pdi = pd
	public AlgebraicOP rewrite() {
		ProjectionOP pp = op.asProjectionOP();
		ScanOP sp = pp.getSubquery().asScanOP();
		if (sp.getSecondaryIndex() != null) {
			if (sp.getSecondaryIndex().getPdi().equals(pp.getPrjDesc())) {
				// the same Pds, so the projection can be removed
				return sp;
			}
		}
		return null;
	}

	@Override
	public boolean applicable() {
		if (op instanceof ProjectionOP
				&& op.asProjectionOP().getSubquery() instanceof ScanOP) {
			return true;
		}
		return false;
	}

}
